﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Net;
using System.Net.Sockets;

namespace For_FS_2013_1_User
{
    class DefaultConnector
    {
        public bool clientAvailable;

        private const int port = 1;
        private TcpClient client;
        private TcpListener listener = null;
        private Thread connect;

        public DefaultConnector()
        {
            listener = new TcpListener(IPAddress.Any, port);
            listener.Start();
            Start();
        }

        private void Start()
        {
            CreateThreads();
            connect.Start();
        }

        private void CreateThreads()
        {
            clientAvailable = false;
            client = new TcpClient();
            connect = new Thread(Connect);
        }

        private void Connect()
        {
            while (!client.Connected)
            {
                client = listener.AcceptTcpClient();
            }
            Console.WriteLine("Default port #1->User Connected");
            clientAvailable = true;
        }

        public void Disconnect()
        {
            Console.WriteLine("Default port #1->User Disconnected");
            if (client != null)
                client.Close();
            Start();
        }

        public void Send(string message)
        {
            if (client.Connected)
            {
                NetworkStream ns = client.GetStream();
                if (ns != null)
                {
                    byte[] buffer = Encoding.Default.GetBytes(message);
                    ns.Write(buffer, 0, buffer.Length);
                }
            }
        }
    }
}
